import axios from 'axios';


export const baseURL = 'http://localhost:8085';

const axiosInstance = axios.create({
    baseURL: '/api',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    // withCredentials: true,
    timeout: 5000
});

const _axios = axios.create(axiosInstance);
// **路由请求拦截**
// http request 拦截器
_axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    let _token = sessionStorage.getItem('_token');
    if (_token) {
        config.headers.Authorization = _token;
    } else {
        sessionStorage.clear();
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
// **路由响应拦截**
// http response 拦截器
_axios.interceptors.response.use(
    function (response) {
        // Do something with response data
        console.log(response)
        if (!response.data.status) {
            if (!sessionStorage.getItem('_token')) {
                sessionStorage.setItem('_token', response.headers.authorization);
                sessionStorage.setItem('id', response.data.data.id);
                sessionStorage.setItem('avatar', response.data.data.avatar);
            }
            return response.data;
        }
        else {
            this.$message.error(response.data.error);
            sessionStorage.clear();
            this.$router.push({
                path: '/login'
            });
            return Promise.reject(new Error(response.data.error));
        }
    },
    function (error) {
        // Do something with response error
        return Promise.reject(error);
    }
);


export default _axios;
